package com.yao_shop.controller;

import com.yao_shop.service.File_service;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@RestController
public class FileController {
    @Autowired
    private File_service service;

    @Value("${com.yao}")
    //获取主机的端口
    private String post;
    //获取ip
    private String host;
    //图片存放的根目录
    private String rootPath ="C:";
    //图片存放的子目录
    private String sonPath="/Users/Administrator/Desktop/image/";
    //获取图片的链接
    private String imgPath;

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @ApiOperation(value = "上传图片",notes = "上传图片并保存图片路径信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgname", value = "图书名字", required = true, example = "猫和老鼠"),
            @ApiImplicitParam(name = "imginfo", value = "图书信息", required = true, example = "猫和老鼠的日常")
    })
    @PostMapping(value = "/uploadimg.do")
    @ResponseBody
    public String upload(@RequestParam("image")MultipartFile file, @RequestParam Map map){
        //返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
        //防止上传空文件导致奔溃
        if (file.isEmpty()){
            return "文件为空";
        }
        //获取本机ip
        try{
            host= InetAddress.getLocalHost().getHostAddress();
        }catch (UnknownHostException e){
            logger.error("get server host Exception e:", e);
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //logger.info("上传的文件名为：" + fileName)
        //设置文件上传后的路径
        String filePath = rootPath +sonPath;
        logger.info("上传的文件路径" + filePath);
        //logger.info("整个图片路径：" + host + ":" + post + sonPath + fileName);
        logger.info("整个图片路径：" + host + ":" + post + "/image/" + fileName);
        //创建文件路径
        File dest = new File(filePath + fileName);

       //String imgpath= (host+":"+post+sonPath+fileName).toString();
        String url= ("127.0.0.1"+":"+post+"/image/"+fileName).toString();

        //获取图片名字  获取图片信息
        Object imgname = map.get("imgname");
        Object imginfo = map.get("imginfo");
        map.put("url",url);
        map.put("imgname",imgname);
        map.put("imginfo",imginfo);

        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        //检测是否存在目录
        if (!dest.getParentFile().exists()){
            //假如文件不存在即重新创建新文件夹防止异常发生
            dest.getParentFile().mkdirs();
        }
        try {
            //transferTo（dest）方法将上传文件 写到服务器上指定的文件
            file.transferTo(dest);
            System.out.println(map);
            //将链接保存到url中
            service.add_file(map);
            return "上传成功";
        }catch (Exception e){
            System.out.println(e);
            return "上传失败";
        }
    }

}
